package net.forsalemall.android;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.taptwo.android.widget.TitleProvider;

import com.github.droidfu.widgets.ImageLoadListener;
import com.github.droidfu.widgets.WebImageView;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.utils.Constants;
import com.utils.HttpUtils;
import com.utils.Utils;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class DealsDetailsActivity extends ListActivity {

	private List<String> fileNames;
	private String adData;
	private JSONObject jAd;
	private int adId;
	private String adDesc;
	private String phoneNo;
	private int viewCount;
	private int imgCount;
	private long time;
	private boolean isFromMyAd;
	private boolean isSold;

	private TextView descView;
	private TextView viewCountView;
	private TextView dateView;
	// private Button favButton;
	private ActionBar actionBar;
	private Action favAction;
	private boolean isFavorite;

	// private ViewFlow viewFlow;
	private ViewFlowAdapter viewFlowAdapter;

	private LayoutInflater mInflater;

	private View topView;

	private ImageLoadListener imageLoadListener = new ImageLoadListener() {

		public void imageLoaded(WebImageView webImageView, Bitmap bitmap) {
			if (bitmap != null && topView != null) {
				int height = (bitmap.getHeight() * topView.getWidth())
						/ bitmap.getWidth();
				webImageView.getLayoutParams().width = topView.getWidth();
				webImageView.getLayoutParams().height = height;
			}
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.deals_details);
			isFromMyAd = getIntent().getBooleanExtra(
					Constants.KEY_IS_FROM_MY_APP, false);
			isSold = getIntent().getBooleanExtra(Constants.KEY_IS_SOLD, false);
			mInflater = (LayoutInflater) this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			topView = mInflater.inflate(R.layout.ad_details_list_content_top,
					null);
			descView = (TextView) topView.findViewById(R.id.desc_view);
			viewCountView = (TextView) topView
					.findViewById(R.id.view_count_view);

			dateView = (TextView) topView.findViewById(R.id.time_view);

			actionBar = (ActionBar) findViewById(R.id.actionbar);
			actionBar.setTitle(getString(R.string.title_ads_details));
			fileNames = new ArrayList<String>();
			adId = getIntent().getIntExtra(Constants.KEY_AD_ID, -1);
			adDesc = getIntent().getStringExtra(Constants.KEY_AD_TEXT);
			isFavorite = false;
			actionBar.setHomeAction(new Action() {
				public void performAction(View view) {
					backToHome();
				}

				public int getDrawable() {
					// TODO Auto-generated method stub
					return R.drawable.ic_title_home_default;
				}
			});

			if (!isSold) {
				actionBar.addAction(new Action() {
					public void performAction(View view) {
						try {
							Intent intent = null;
							if (phoneNo != null) {
								intent = new Intent(Intent.ACTION_DIAL, Uri
										.parse("tel:" + phoneNo));
							} else {
								intent = new Intent(Intent.ACTION_DIAL);
							}
							startActivity(intent);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					public int getDrawable() {
						return R.drawable.ic_menu_call;
					}
				});
				actionBar.addAction(new Action() {
					public void performAction(View view) {
						try {
							Intent intent = null;
							if (phoneNo != null) {
								intent = new Intent(Intent.ACTION_SENDTO,
										Uri.parse("smsto:" + phoneNo));
							} else {
								intent = new Intent(Intent.ACTION_SENDTO);
							}
							startActivity(intent);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					public int getDrawable() {
						return R.drawable.ic_menu_send;
					}
				});
				
				favAction = new Action() {
					public void performAction(View view) {
						try {
							addRemoveFavorite();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					public int getDrawable() {
						return isFavorite ? R.drawable.ic_menu_unfavorite
								: R.drawable.ic_menu_favorite;
					}
				};
				actionBar.addAction(favAction);
			}
			actionBar.setDisplayHomeAsUpEnabled(true);
			descView.setText(adDesc);
			loadData();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void loadData() {
		new AsyncTask<String, String, String>() {
			private ProgressDialog progressDialog;

			protected void onPreExecute() {
				try {
					progressDialog = Utils.getProgressDialog(
							DealsDetailsActivity.this, null,
							getString(R.string.loading));
					progressDialog.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			protected String doInBackground(String... arg0) {
				try {
					fileNames.clear();

					fileNames.add("");

					adData = HttpUtils.getAdDetails(adId,
							Utils.getDeviceId(DealsDetailsActivity.this));
					jAd = new JSONObject(adData);
					if (jAd != null) {
						viewCount = jAd.getInt("view_count");
						imgCount = jAd.getInt("img_count");
						phoneNo = jAd.getString("pn");
						time = System.currentTimeMillis()
								- (jAd.getLong("time_diff") * 1000);
						isFavorite = (jAd.getInt("is_favorite") != 0);
						JSONArray ja = jAd.getJSONArray("img_file_names");
						for (int i = 0; i < ja.length(); i++) {
							fileNames.add(ja.getString(i));
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(String unused) {
				try {
					dateView.setText(Constants.SIMPLE_DATE_FORMAT
							.format(new Date(time)));

					viewCountView.setText(String.format(
							getString(R.string.view_count),
							Integer.toString(viewCount)));
					
					if (!isSold){
						actionBar.setTitle(phoneNo);
						if (!isFromMyAd) {
							actionBar.removeAction(favAction);
							actionBar.addAction(favAction);
						}
					}

					if (fileNames.size() > 0) {
						viewFlowAdapter = new ViewFlowAdapter(fileNames);
						setListAdapter(viewFlowAdapter);
					}
					progressDialog.dismiss();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute();
	}

	private void addRemoveFavorite() {
		new AsyncTask<String, String, String>() {
			private ProgressDialog progressDialog;

			protected void onPreExecute() {
				try {
					progressDialog = Utils.getProgressDialog(
							DealsDetailsActivity.this, null,
							getString(R.string.loading));
					progressDialog.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			protected String doInBackground(String... arg0) {
				try {
					if (isFavorite) {
						HttpUtils.removeFromFavorite(
								Utils.getDeviceId(DealsDetailsActivity.this),
								Integer.toString(adId));
						isFavorite = false;
					} else {
						HttpUtils.addToFavorite(
								Utils.getDeviceId(DealsDetailsActivity.this),
								Integer.toString(adId));
						isFavorite = true;
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(String unused) {
				try {
					actionBar.removeAction(favAction);
					actionBar.addAction(favAction);
					progressDialog.dismiss();
					Utils.showAlertMessage(DealsDetailsActivity.this,null,
							isFavorite?getString(R.string.favorited_ad): getString(R.string.unfavorited_ad));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute();
	}

	private void backToHome() {
		try {
			startActivity(new Intent(this, HomeActivity.class)
					.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public class ViewFlowAdapter extends BaseAdapter implements TitleProvider {

		private List<String> items;

		public ViewFlowAdapter(List<String> items) {
			this.items = items;

		}

		public int getCount() {
			return (items == null) ? 0 : items.size();
		}

		public Object getItem(int arg0) {
			Object ret = null;
			if (items != null && items.size() > arg0) {
				ret = items.get(arg0);
			}
			return ret;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (position == 0) {
				convertView = topView;
			} else {
				convertView = mInflater.inflate(
						R.layout.ad_details_list_content_bottom, null);
				WebImageView wiv = (WebImageView) convertView
						.findViewById(R.id.list_image);
				wiv.setImageLoadListener(imageLoadListener);	
				wiv.setImageUrl(HttpUtils.getFileUrl(Constants.getAdImgDirName(),
						items.get(position)));
				wiv.loadImage();
			}
			return convertView;
		}

		class ViewHolder {
			WebImageView wiv;
		}

		public String getTitle(int position) {
			// TODO Auto-generated method stub
			return items.get(position);
		}
	}
}
